package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.eventTrack.CDPTrackReportManager;
import com.eventTrack.TXReportManager;
import com.jaeger.library.StatusBarUtil;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.clickutils.NoDoubleClickUtils;
import com.mediacloud.app.assembly.photoview.PhotoViewAttacher.OnViewTapListener;
import com.mediacloud.app.assembly.util.FileFormatUtils;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.interfaces.IPermissionsAgree;
import com.mediacloud.app.model.interfaces.PermissionUtil;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.GroupPhotoDataReciver;
import com.mediacloud.app.model.news.GroupPhotoDataReciver.PhotoItem;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.model.AddHistoryParamsData;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.CollectionController;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.HistoryInvoker;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.newsmodule.view.BaseSpiderViewX;
import com.mediacloud.app.newsmodule.view.HackyViewPager;
import com.mediacloud.app.newsmodule.view.PictureViewX;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.util.ClickUtils;
import com.model.PhotoInfo;
import com.zimeiti.details.MediaAuthorDetailActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;

import static com.mediacloud.app.cloud.qrcodescan.UrlToolKt.getOriginImageForThumbnailImage;
import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

/**
 * 组图，图集
 *
 * @author wjj
 */
@SuppressWarnings("ALL")
public class GroupPhotoNewsDetailActivity extends StyleSetActivity implements DataInvokeCallBack<ArticleItemReciver> {
    private boolean isImgNewsJump;
    private RelativeLayout downloadLayout;
    private ImageView downloadBack, downloadIco;
    private TextView downloadNumb, text_editor, text_source;
    private TextView tv_look_origin_logo;
    private ViewPager mViewPager;
    private ArrayList<PhotoInfo> mPhotoUrls = new ArrayList<PhotoInfo>();
    protected List<PhotoItem> photos;
    protected boolean isDisposed;
    public TextView tvAuthor, tvPlayCount, tvPublishData;

    protected LinearLayout bottomTextDesLayout;
    protected RelativeLayout photoGroupRootView;
    protected FrameLayout photoContent;
    protected View bottomRelativeView;
    protected TextView imageTitle, imageDes;
    NewsDetailInvoker sewsDetailInvoker;
    protected RelativeLayout mTitileBar;
    BaseSpiderViewX spiderView;
    HashMap<Integer, PictureViewX> pictureViewXHashMap = new HashMap<>();

    View mLine;
    boolean hideImageTitle = false;

    private LinearLayout bottomOpratateLayout;
    private boolean isLocalSpinder = true;
    long mTyReportStartTime = 0;
    long mTyReportEndTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       /* if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            }
            getWindow().setAttributes(lp);

            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.BLACK);
            getWindow().setNavigationBarColor(Color.BLACK);

        }

        StatusBarUtil.setDarkMode(this);
        //是不是图文新闻跳转的
        isImgNewsJump = getIntent().getBooleanExtra("isImgNewsJump", false);
        catalogItem = getIntent().getParcelableExtra("catalog");
        articleItem = getIntent().getParcelableExtra("data");

        try {
            if (catalogItem == null)
                catalogItem = new CatalogItem();
            catalogItem.setCatalog_type(getIntent().getStringExtra("category"));
            catalogItem.setCatid(getIntent().getStringExtra("navigate_id"));
            if (articleItem == null) {
                articleItem = new ArticleItem();
                articleItem.setId(Long.parseLong(getIntent().getStringExtra("article_id")));
                articleItem.setSummary(getIntent().getStringExtra("summary"));
                articleItem.setTitle(getIntent().getStringExtra("title"));
                articleItem.setUrl(getIntent().getStringExtra("url"));
                articleItem.setIsAdvertisement(getIntent().getIntExtra("isAdvertisement", 0));
                articleItem.setIsBarrage(getIntent().getIntExtra("isBarrage", 0));
                articleItem.setReferSourceID(getIntent().getStringExtra("ReferSourceID"));
                articleItem.setIsComment(getIntent().getStringExtra("isComment"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (articleItem != null) {
            isLocalSpinder = articleItem.isLocalSpinder();
            sendExposureEvent();
        }

        historyInvoker = new HistoryInvoker();

        hideImageTitle = getIntent().getBooleanExtra("hideImageTitle", false);
        sewsDetailInvoker = new NewsDetailInvoker(this);
        initView();
        loadImageNewsDetail();

        decideTitileBarStyle();
        setTitle("");
        // setNewsTitle();
//        if (!isImgNewsJump)
//            showStateView(TYPE_LOADING, false);
        onPageStart();
        showPageTransition();
        mTitileBar.setBackgroundColor(Color.TRANSPARENT);
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mTitileBar.getLayoutParams();
        lp.topMargin = StatusBarUtil.getStatusBarHeight(this);
        mTitileBar.setLayoutParams(lp);
        if (articleItem != null && articleItem.getLocalShareType() == -1) {
            if (mTitlebar_More != null) {
                mTitlebar_More.setVisibility(View.GONE);
            }
            if (bottomOpratateLayout != null) {
                bottomOpratateLayout.setVisibility(View.GONE);
            }
            if (bottomRelativeView != null) {
                bottomRelativeView.setVisibility(View.GONE);
            }
        }
        photoGroupRootView.setBackgroundColor(Color.BLACK);

        tvLetmeSay.setTextColor(Color.parseColor("#FF999999"));

        if (bottomRelativeView.getVisibility() == View.VISIBLE) {//从文稿进入不添加历史记录
            addHistory();
        }

        //设置笑脸颜色白色
        ivFace.setImageResource(R.drawable.icon_face);

        if (retryTips != null) {
            retryTips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!currentState.equals(TYPE_LOADING)) {
                        showStateView(TYPE_LOADING, false);
                        loadImageNewsDetail();
                        decideTitileBarStyle();
                        setTitle("");
                        // setNewsTitle();
//        if (!isImgNewsJump)
//            showStateView(TYPE_LOADING, false);
                        onPageStart();
                        showPageTransition();
                        mTitileBar.setBackgroundColor(Color.TRANSPARENT);
                        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mTitileBar.getLayoutParams();
                        lp.topMargin = StatusBarUtil.getStatusBarHeight(GroupPhotoNewsDetailActivity.this);
                        mTitileBar.setLayoutParams(lp);
                        if (articleItem != null && articleItem.getLocalShareType() == -1) {
                            if (mTitlebar_More != null) {
                                mTitlebar_More.setVisibility(View.GONE);
                            }
                            if (bottomOpratateLayout != null) {
                                bottomOpratateLayout.setVisibility(View.GONE);
                            }
                            if (bottomRelativeView != null) {
                                bottomRelativeView.setVisibility(View.GONE);
                            }
                        }
                        photoGroupRootView.setBackgroundColor(Color.BLACK);

                        tvLetmeSay.setTextColor(Color.parseColor("#FF999999"));

                        if (bottomRelativeView.getVisibility() == View.VISIBLE) {//从文稿进入不添加历史记录
                            addHistory();
                        }

                        //设置笑脸颜色白色
                        ivFace.setImageResource(R.drawable.icon_face);
                    }
                }
            });
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle arg0) {
//        super.onSaveInstanceState(arg0);
    }

    @Override
    public void setWhiteBottomButton() {
        isWhiteColor = true;
    }

    @Override
    protected String getContent_show_top_color() {
        return "#FFFFFF";
    }

    @Override
    protected boolean openTitleBarSetting() {
        return true;
    }


    @Override
    public int getStatusBarColor() {
        return Color.TRANSPARENT;
    }

    @Override
    protected boolean getFitSystemWindow() {
        return false;
    }

    private HistoryInvoker historyInvoker;

    private void addHistory() {
        AddHistoryParamsData paramsData = new AddHistoryParamsData();
        paramsData.source = CollectionController.convertToSource(catalogItem);
        if (articleItem.getId() > 0) {
            paramsData.source_id = articleItem.getId();
        } else {
            if (!TextUtils.isEmpty(articleItem.getReferTarget())) {
                try {
                    paramsData.source_id = Long.parseLong(articleItem.getReferTarget());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        paramsData.summary = articleItem.getSummary();
        paramsData.title = articleItem.getTitle();
        paramsData.type = articleItem.getType() + "";
        paramsData.url = articleItem.getUrl();
        paramsData.logo = articleItem.getLogo();
        paramsData.publishdate_format = articleItem.getPublishdate_format();
        paramsData.isFromEpaper = articleItem.isEPaper ? "1" : "0";
        paramsData.logoImgSize = articleItem.getLogoImgSize();
        historyInvoker.addHistory(UserInfo.getUserInfo(this).getUserid(), paramsData, null);
    }


    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    protected void setNewsTitle() {
        int base = serverAppConfigInfo.getBase();
        if (base == TitileType.FRAME) {
            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? articleItem.getTitle() : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }
    }


    protected boolean needLoadTopSecondBgSkin() {
        return super.subClassgetNeedTopSecondBgSkin();
    }

    protected NavigateBarStyle getNewsDetailNavigateBarStyle() {
        return getAppServerConfigInfo(this).getPhotoNewsBar();
    }


    protected void initView() {
        mTitlebar_More = findViewById(R.id.mTitlebar_More);
        spiderView = Utility.findViewById(mRootView, R.id.spiderView);
        rlayout_back = Utility.findViewById(mRootView, R.id.rlayout_back);
        bottomTextDesLayout = findViewById(R.id.bottomTextDesLayout);
        photoGroupRootView = findViewById(R.id.photoGroupRootView);
        text_editor = findViewById(R.id.text_editor);
        text_source = findViewById(R.id.text_source);
        imageTitle = findViewById(R.id.imageTitle);
        mTitileBar = findViewById(R.id.rlTitleBar);
        if (hideImageTitle) imageTitle.setVisibility(View.INVISIBLE);
        imageDes = findViewById(R.id.imageDes);
        photoContent = findViewById(R.id.photoContent);
        bottomRelativeView = findViewById(R.id.relative_bottom);
        bottomOpratateLayout = findViewById(R.id.linear_news_bottom_back_bar);
        mViewPager = new HackyViewPager(this);
        photoContent.addView(mViewPager, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) photoContent.getLayoutParams();
        lp.topMargin = StatusBarUtil.getStatusBarHeight(this);
        photoContent.setLayoutParams(lp);

        // mViewPager.setFitsSystemWindows(true);
        bottomBarLayout.setBackgroundColor(Color.TRANSPARENT);
        mLine = findViewById(R.id.photo_line);
        mLine.setVisibility(View.GONE);
        mRootView.setBackgroundColor(Color.BLACK);
        intDownLoadView();
        //组图的 我来说两句 评论框背景是黑色的
//        Drawable drawable = tvLetmeSay.getBackground().mutate();
//        GradientDrawable gradientDrawable = (GradientDrawable) drawable;
//        gradientDrawable.setColor(Color.parseColor("#26F7F7F7"));
        Drawable drawable = ivFace.getDrawable();
        drawable.setTint(Color.WHITE);
        ivFace.setImageDrawable(drawable);
        tvLetmeSay.setBackground(null);
        tvLetmeSay.setBackgroundColor(ContextCompat.getColor(this, R.color.c_303030));
        tvLetmeSay.setHint("我来说几句");
        tvPlayCount = findViewById(R.id.tvPlayCount);
        tvAuthor = findViewById(R.id.tvAuthor);
        tvPublishData = findViewById(R.id.tvPublishData);
        setCommentPhotoColor();
        findViewById(R.id.mTop_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(this).getNewsDetailConfig().getLinkedHashSet();
        if(!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON)){
            mTitlebar_More.setVisibility(View.GONE);
        }else {
            mTitlebar_More.setVisibility(View.VISIBLE);
        }
        mTitlebar_More.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                shareWrap.show(mRootView);
            }
        });
    }

    /* @Override
    protected void showLikeButtonWithConfig(boolean show) {
        super.showLikeButtonWithConfig(show);
    }*/

    @Override
    public void showStateView(String type, boolean forceDefault) {
        super.showStateView(type, forceDefault);
    }

    /**
     * 图片下载相关
     */
    protected void intDownLoadView() {

        downloadLayout = findViewById(R.id.downloadLayout);
        downloadNumb = findViewById(R.id.downloadNumb);
        tv_look_origin_logo = findViewById(R.id.tv_look_origin_logo);
        downloadBack = findViewById(R.id.downloadBack);
        downloadBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_look_origin_logo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TXReportManager.getInstance().app_jhapp_content_detail_interact("查看原图","","",articleItem);

                ClickUtils.delayClickable(v);
                if (mViewPager != null
                        && (mPhotoUrls != null && mPhotoUrls.size() > 0)
                        && mViewPager.getCurrentItem() < mPhotoUrls.size()) {
                    if (!mPhotoUrls.get(mViewPager.getCurrentItem()).isLocalOriginLogo) {
                        mPhotoUrls.get(mViewPager.getCurrentItem()).isLocalOriginLogo = true;
                        pictureViewXHashMap.get(mViewPager.getCurrentItem()).setImageURL(mPhotoUrls.get(mViewPager.getCurrentItem()).logo,false);
                        tv_look_origin_logo.setVisibility(View.GONE);
                    }

                }
            }
        });
        downloadIco = findViewById(R.id.downloadIco);
        downloadIco.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                TXReportManager.getInstance().app_jhapp_content_detail_interact("下载","","",articleItem);

                if (NoDoubleClickUtils.isDoubleClick()) {
                    return;
                }
                PermissionUtil.INSTANCE.invokeStoragePermission(GroupPhotoNewsDetailActivity.this, new IPermissionsAgree() {
                    @Override
                    public void onAgree() {
                        new SaveImage().execute(mPhotoUrls.get(mViewPager.getCurrentItem()).logo);
                        if (photos != null && !photos.isEmpty() && mViewPager != null) {
                            String pictureName = mViewPager.getCurrentItem() + photos.get(mViewPager.getCurrentItem()).getName() + mViewPager.getCurrentItem();
                            //TyReportManager.getInstance().save_picture(pictureName, org.xutils.common.util.MD5.md5(catalogItem.getCatname()), catalogItem.getCatname()+"详情页");
                        }
                    }

                    @Override
                    public void onRefuse() {

                    }

                    @Override
                    public void hasPermissions() {
                        new SaveImage().execute(mPhotoUrls.get(mViewPager.getCurrentItem()).logo);
                        if (photos != null && !photos.isEmpty() && mViewPager != null) {
                            String pictureName = mViewPager.getCurrentItem() + photos.get(mViewPager.getCurrentItem()).getName() + mViewPager.getCurrentItem();
                            //TyReportManager.getInstance().save_picture(pictureName, org.xutils.common.util.MD5.md5(catalogItem.getCatname()), catalogItem.getCatname()+"详情页");
                        }
                    }
                });


            }
        });
    }


    protected void decideTitileBarStyle() {
        if (isShowComment(articleItem)) {
            showCommentRelativeView(true);
        } else {
            showCommentRelativeView(false);
        }
    }
//20230110 等待下次版本更新，本次先关闭优化
//    @Override
//    protected int getBottemBarColor() {
//        return Color.BLACK;
//    }

    public void loadImageNewsDetail() {
        if (!TextUtils.isEmpty(articleItem.getReal_title())) {
            imageTitle.setText(articleItem.getReal_title());
        } else {
            if (!TextUtils.isEmpty(articleItem.getTitle())){
                imageTitle.setText(articleItem.getTitle());
            }else {
                imageTitle.setText(articleItem.getSummary());
            }
        }
        imageTitle.getPaint().setFakeBoldText(true);
        //现在屏掉直接设置详情 从外面把id给进来的时候    重新去取一次详情  主要是有些搜索的地方要用到

        String navigate_id = catalogItem.getCatid();

        if (!isImgNewsJump) {
            sewsDetailInvoker.getArticleById("" + articleItem.getId(), navigate_id);
        } else {
            showCollectWithConfig(false);
            showShareWithConfig(false);
            showCommentButtonWithConfig(false);
            showLikeButtonWithConfig(false);
            setImages(articleItem);
            // mTitlebar_MoreContainer.setVisibility(View.GONE);
            closeStateView();
            int index = getIntent().getIntExtra("index", 0);
            if (index > 0 && index < mPhotoUrls.size()) {
                mViewPager.setCurrentItem(index);
                updateLookOriginLogoUI(index);
            } else {
                updateLookOriginLogoUI(0);
            }
            if (true/*"zgjh".equals(AppFactoryGlobalConfig.getAppServerConfigInfo(this).code_method)*/) {
                if (articleItem.getSpider() != null) {
                    spiderView.getSpiderAuthor().setTextColor(Color.WHITE);
                    spiderView.setDate(articleItem);
                    if (!isLocalSpinder) {
                        spiderView.setVisibility(View.GONE);
                    }
                }
                tvPlayCount.setText(StringUtils.toTenThousand(articleItem.getHitCount_format()) + "浏览");
                if (TextUtils.isEmpty(articleItem.getAuthor())) {
                    tvAuthor.setVisibility(View.GONE);
                } else {
                    tvAuthor.setVisibility(View.VISIBLE);
                    tvAuthor.setText(articleItem.getAuthor());
                }
                tvPublishData.setText(articleItem.getPublishdate_format());
            } else {
                findViewById(R.id.layout_author).setVisibility(View.GONE);
            }

        }
    }


    protected void setImages(ArticleItem item) {
        closeStateView();
        try {

            photos = new ArrayList<GroupPhotoDataReciver.PhotoItem>();
            JSONArray jsonArray = new JSONArray(item.getImage());

            if (jsonArray.length() == 0) {
                mPhotoUrls.add(new PhotoInfo());
                GroupPhotoDataReciver.PhotoItem photoItem = new GroupPhotoDataReciver.PhotoItem();
                photoItem.setImage("");
                photoItem.setThumb("");
                photoItem.setNote("");
                photos.add(photoItem);
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                GroupPhotoDataReciver.PhotoItem photoItem = new GroupPhotoDataReciver.PhotoItem();
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                String url = getOriginImageForThumbnailImage(jsonObject.optString("src", ""));
                String note = jsonObject.optString("info", item.getTitle());
                photoItem.setImage(url);
                photoItem.setThumb(url);
                photoItem.setNote(note);
                photos.add(photoItem);

                mPhotoUrls.add(new PhotoInfo(url));
            }
        } catch (Exception e) {
            e.printStackTrace();
            //			Log.w(TAG, e.getMessage());
            if (mPhotoUrls.size() == 0) {
                mPhotoUrls.add(new PhotoInfo());
            }
        }
        mViewPager.setAdapter(new SamplePagerAdapter(mPhotoUrls));
        mViewPager.setOffscreenPageLimit(mPhotoUrls.size());
        //	mViewPager.setOffscreenPageLimit(mPhotoUrls.size());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                updateLookOriginLogoUI(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        updateLookOriginLogoUI(0);
    }


    /**
     * 更新查看原图 UI
     *
     * @param position 页码下标
     */
    public void updateLookOriginLogoUI(int position) {
        if (mViewPager != null
                && (mPhotoUrls != null && mPhotoUrls.size() > 0)
                && position < mPhotoUrls.size()) {
            /*if (mPhotoUrls.get(position).isLocalOriginLogo) {
                tv_look_origin_logo.setVisibility(View.GONE);
            } else {
                tv_look_origin_logo.setVisibility(View.VISIBLE);
            }*/
            tv_look_origin_logo.setVisibility(View.VISIBLE);

        }
    }

    private class SamplePagerAdapter extends PagerAdapter {
        private ArrayList<PhotoInfo> urls;
        private int urlsSize;
        private int mPosition = 0;
        boolean hideNote = false;

        public SamplePagerAdapter(ArrayList<PhotoInfo> urls) {
            this.urls = urls;
            urlsSize = urls.size();
        }

        @Override
        public int getCount() {
            return urlsSize;
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            if (position >= urlsSize) {
                return null;
            }
            PictureViewX pictureViewX = new PictureViewX(container.getContext());
            pictureViewX.setId(View.generateViewId());
            if (!isImgNewsJump){
                pictureViewX.mAttacher.setOnViewTapListener(new OnViewTapListener() {
                    @Override
                    public void onViewTap(View view, float x, float y) {
                        hideNote = !hideNote;
                        if (hideNote) {
                            imageTitle.setVisibility(View.GONE);

                            mLine.setVisibility(View.GONE);
//                        if (articleItem!=null&&articleItem.getLocalShareType()==-1) {
                            bottomOpratateLayout.setVisibility(View.GONE);
                            bottomRelativeView.setVisibility(View.INVISIBLE);
//                        }else{
//                            bottomRelativeView.setVisibility(View.VISIBLE);
//                            bottomOpratateLayout.setVisibility(View.VISIBLE);
//                        }
                            if (mTitlebar_More != null) {
                                mTitlebar_More.setVisibility(View.GONE);
                            }
                            if (spiderView != null) {
                                spiderView.setVisibility(View.GONE);
                            }
                            bottomTextDesLayout.setVisibility(View.GONE);
                            downloadLayout.setVisibility(View.VISIBLE);
                        } else {
                            mLine.setVisibility(View.GONE);
                            imageTitle.setVisibility(View.VISIBLE);
                            if (articleItem != null && articleItem.getLocalShareType() == -1) {
                                bottomOpratateLayout.setVisibility(View.GONE);
                                bottomRelativeView.setVisibility(View.INVISIBLE);
                                if (mTitlebar_More != null) {
                                    mTitlebar_More.setVisibility(View.GONE);
                                }
                                if (spiderView != null) {
                                    spiderView.setVisibility(View.GONE);
                                }
                            } else {
                                if (mTitlebar_More != null) {
                                    mTitlebar_More.setVisibility(View.VISIBLE);
                                }
                                if (spiderView != null) {
                                    spiderView.setVisibility(View.VISIBLE);
                                }
                                bottomOpratateLayout.setVisibility(View.VISIBLE);
                                bottomRelativeView.setVisibility(View.VISIBLE);
                            }
                            bottomTextDesLayout.setVisibility(View.VISIBLE);
                            downloadLayout.setVisibility(View.GONE);

                        }
                    }
                });
            }
            else {
                spiderView.setVisibility(View.GONE);
                imageTitle.setVisibility(View.GONE);
                downloadLayout.setVisibility(View.VISIBLE);
                mLine.setVisibility(View.GONE);
                bottomOpratateLayout.setVisibility(View.GONE);
                bottomRelativeView.setVisibility(View.GONE);
                bottomTextDesLayout.setVisibility(View.GONE);
            }
            pictureViewX.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            if (urls.get(position).isLocalOriginLogo) {
                pictureViewX.setImageURL(urls.get(position).logo);
            } else {
                pictureViewX.setThumbnailImageURL(urls.get(position).logo);
            }
            container.addView(pictureViewX, 0);
            pictureViewXHashMap.put(position, pictureViewX);
            return pictureViewX;
        }

        @Override
        public void setPrimaryItem(View container, int position, Object object) {
            if (photos.size() == 0)
                return;
            int mainColor = serverAppConfigInfo.getMainColor();
            //			float fontSize=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, getResources().getDisplayMetrics());
            float fontSize = getResources().getDimension(R.dimen.dimen17);
            float fontSize2 = getResources().getDimension(R.dimen.dimen17);
            SpannableString spannableString = new SpannableString((position + 1) + "/" + urlsSize) /*+ "  "+articleItem.getTitle())*/;

            ForegroundColorSpan focusTextColor = new ForegroundColorSpan(Color.parseColor("#FF35C5CE"));
            spannableString.setSpan(focusTextColor, 0, position >= 9 ? 2 : 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//            spannableString.setSpan(new AbsoluteSizeSpan((int) fontSize), 0, position >= 9 ? 2 : 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//            spannableString.setSpan(new AbsoluteSizeSpan((int) fontSize2), position >= 9 ? 2 : 1, position >= 9 ? 2 : 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            imageTitle.setText(spannableString);
            if (!TextUtils.isEmpty(articleItem.getReal_title())){
                imageTitle.append("   " + articleItem.getReal_title());

            }else {
                imageTitle.append("   " + articleItem.getTitle());

            }
            downloadNumb.setText(spannableString);
            mPosition = position;
            String note = photos.get(position).getNote();
            if (TextUtils.isEmpty(note) && articleItem != null)
                note = articleItem.getTitle();
            imageDes.setText(note);
            if (articleItem != null) {
                if (!TextUtils.isEmpty(articleItem.Author) && !"null".equals(articleItem.Author)) {
                    text_editor.setText("责编：" + articleItem.Author);
                }
                if (!TextUtils.isEmpty(articleItem.getReferName()) && !"null".equals(articleItem.getReferName())) {
                    text_source.setText("来源：" + articleItem.getReferName());
                }
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        //		public int getCurrentPosition() {
        //			return mPosition;
        //		}


        @Nullable
        @Override
        public Parcelable saveState() {
            Parcelable parcelable = super.saveState();
            if (parcelable instanceof Bundle) {
                ((Bundle) parcelable).putParcelableArray("states", null);
            }
            return parcelable;
        }

    }

    @Override
    protected void onDestroy() {
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis();
        }
        articleItem.setPreview(articleItem.getTitle());
        if (!TextUtils.isEmpty(MediaAuthorDetailActivity.intentId))
            CDPTrackReportManager.getInstance().DistrictCMContentDetailView(articleItem,((System.currentTimeMillis() - inTime) / 1000));
        else
            CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,(System.currentTimeMillis()-inTime)/1000);

        if (pictureViewXHashMap != null) {
            pictureViewXHashMap.clear();
        }
        isDisposed = true;
        if (sewsDetailInvoker != null) {
            sewsDetailInvoker.destory();
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;
        if (photos != null)
            photos.clear();
        sewsDetailInvoker = null;
        super.onDestroy();
        catalogItem = null;
        articleItem = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
    }


    @Override
    public int getLayoutResID() {
        return R.layout.activity_photonews_detail;
    }


    protected void intoLogin(Context context) {
        //     ToastUtil.show(context, R.string.please_login);
//        Intent intent = new Intent();
//        intent.setClassName(context, ModuleReferenceConfig.LoginActivity);
//        context.startActivity(intent);
        LoginUtils.request_source="图集";
        LoginUtils.invokeLogin(context);
    }

    @Override
    public void success(ArticleItemReciver data) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (data.state && data.articleItem != null) {
            CDPTrackReportManager.getInstance().setCurrentPageName(articleItem.getTitle());
            mTyReportEndTime = mTyReportStartTime = System.currentTimeMillis();
            if (articleItem.getFromComponent() != 1)
                // setNewsTitle();
                articleItem = data.articleItem;
            shareWrap.init(articleItem, catalogItem);
            ReportKit.INSTANCE.escalationArticle(articleItem.getId()+"", articleItem.getTitle(),articleItem.getPublishdate(),articleItem.getAddUser());
            if (true/*"zgjh".equals(AppFactoryGlobalConfig.getAppServerConfigInfo(this).code_method)*/) {
                if (articleItem.getSpider() != null) {
                    BaseSpiderViewX spiderView = findViewById(R.id.spiderView);
                    spiderView.getSpiderAuthor().setTextColor(Color.WHITE);
                    spiderView.setDate(articleItem);
                    if (!isLocalSpinder) {
                        spiderView.setVisibility(View.GONE);
                    }

                }
                tvPlayCount.setText(StringUtils.toTenThousand(articleItem.getHitCount_format()) + "浏览");
//                tvPlayCount.setText(articleItem.getHitCount_format() + "浏览");
                if (TextUtils.isEmpty(articleItem.getAuthor())) {
                    tvAuthor.setVisibility(View.GONE);
                } else {
                    tvAuthor.setVisibility(View.VISIBLE);
                    tvAuthor.setText(articleItem.getAuthor());
                }
                tvPublishData.setText(articleItem.getPublishdate_format());
            } else {
                findViewById(R.id.layout_author).setVisibility(View.GONE);
            }
            refreshBottomStyle(data.articleItem, 1);
            UserRecommend.addItemKeyWord(articleItem, this);
            if (!TextUtils.isEmpty(articleItem.getReal_title()))
                imageTitle.setText(articleItem.getReal_title());
            else
                imageTitle.setText(articleItem.getTitle());

            readStatus();
            decideTitileBarStyle();
            AddMedalStatistics.addMedalStatistics(this); //勋章统计
            startAddIntegralCounter();
            setImages(data.articleItem);
        } else {
            fault(null);
        }
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(GroupPhotoNewsDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0", articleItem);
            }
        });
    }

    @Override
    public void fault(Object data) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        setImages(articleItem);
        if (null == data) {
            showStateView(TYPE_NO_CONTENT, false);
        } else {
            showStateView(TYPE_LOADING, false);
        }
    }


    /***
     * 功能：用线程保存图片
     *
     * @author wangyp
     */
    public class SaveImage extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            if (isFinishing() || isDestroyed()) {
                return null;
            }
            String result = "";
            InputStream inputStream = null;
            HttpURLConnection conn = null;
            FileOutputStream outStream = null;
            try {
                String sdcard = Environment.getExternalStorageDirectory().toString();
                File file = new File(sdcard + "/Download");
                if (!file.exists()) {
                    file.mkdirs();
                }
                final String SUFFIX = ".imgtype";
                file = new File(sdcard + "/Download/" + getResources().getString(R.string.tenantid) + "_" + new Date().getTime() + SUFFIX);
                   // 关键：解析真实路径，防止符号链接绕过
                String canonicalPath = file.getCanonicalPath();
                String allowedDir = new File(sdcard, "Download").getCanonicalPath();

                if (!canonicalPath.startsWith(allowedDir)) {
                    throw new SecurityException("非法路径: " + canonicalPath);
                }

                
                URL url = new URL(params[0]);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                conn.setDoInput(true);
                conn.connect();
                Log.e("", "==dow== " + conn.getResponseCode());
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                    byte[] buffer = new byte[4096];
                    int len = 0;

                    outStream = new FileOutputStream(file);
                    while ((len = inputStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();
                    String path = file.getAbsolutePath();
                    FileFormatUtils.FileType fileType = FileFormatUtils.getType(path);
                    if (fileType == FileFormatUtils.FileType.GIF) {
                        path = path.replace(SUFFIX, ".gif");
                    } else if (fileType == FileFormatUtils.FileType.JPEG) {
                        path = path.replace(SUFFIX, ".jpg");
                    } else if (fileType == FileFormatUtils.FileType.PNG) {
                        path = path.replace(SUFFIX, ".png");
                    } else if (fileType == FileFormatUtils.FileType.BMP) {
                        path = path.replace(SUFFIX, ".bmp");
                    }
                    File renamedFile = new File(path);
                    file.renameTo(renamedFile);
                    result = getResources().getString(R.string.image_besaved);
                    Utility.insertIntoMediaStore(getApplicationContext(), false, renamedFile, renamedFile.lastModified());
                } else {
                    result = getResources().getString(R.string.image_save_failed);
                }
            } catch (Exception e) {

                result = getResources().getString(R.string.image_save_failed);
            } finally {
                try {
                    if (outStream != null) {
                        outStream.flush();
                        outStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (conn != null) {
                    conn.disconnect();
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            if (isFinishing() || isDestroyed()) {
                return;
            }
            FunKt.toastCenter(GroupPhotoNewsDetailActivity.this, result, false);

        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }


    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    public boolean getBarTextColorIsDefault() {
        return false;
    }

    @Override
    public void finish() {
        ReportKit.INSTANCE.escalationArticleTime();
        super.finish();
    }
}